<template>
	<view>
		<block v-if="isCustom">
			<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="maxCount"
				:previewFullImage="true" width="158" height="98" :accept="accept" maxDuration="">
				<image v-if="isCustom" src="https://qykh.shopec.com.cn/image-server/dz/cer_upload.png"
					style="width: 316rpx;height: 196rpx;"></image>
			</u-upload>
		</block>
		
		<block v-else>
			<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="maxCount"
				:previewFullImage="true" :accept="accept">
			</u-upload>
		</block>

	</view>
</template>

<script>
	import {
		uploadfiles
	} from '@/api/mine-api.js'
	export default {
		name: 'sr-upload',
		data() {
			return {
				fileList: [],
				resultPathList: []
			}
		},
		props: {
			// 最大上传数量
			maxCount: {
				type: [String, Number],
				default: 3
			},
			isCustom: {
				type: Boolean,
				default: false
			},
			accept:{
				type: String,
				default: 'image'
			}
		},
		mounted() {},
		methods: {
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1);
				this.resultPathList.splice(event.index, 1);
				this.$emit('uploadResult', Object.assign(this.fileList));
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				console.log(lists);
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.upload(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.data.url
					}))
					console.log('filelist', this.fileList);
					this.resultPathList.splice(fileListLen, 1, result.data.saveUrl)
					fileListLen++
				}
				this.$emit('uploadResult', this.resultPathList);

			},

			/**
			 * 上传图片
			 */
			async upload(url) {
				uni.showToast({
					title: '图片上传中...',
					icon: 'loading'
				});
				try {
					const result = await uploadfiles({
						name: 'files',
						filePath: url,
					});
					uni.showToast({
						title: '图片上传成功',
						icon: 'success'
					});
					return result;
				} catch (error) {
					uni.showToast({
						title: error,
						icon: 'error'
					});
				}
			}
		}

	}
</script>

<style lang="scss" scoped>

</style>
